<template>
  <van-nav-bar
      :title="title"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
  >
    <template #right>
      <van-icon name="search" size="18"/>
    </template>
  </van-nav-bar>
  <div id="content">
    <router-view/>
  </div>
  <van-tabbar route @change="onChange">
    <van-tabbar-item to="/" icon="home-o" name="index">主页</van-tabbar-item>
    <van-tabbar-item icon="friends-o" name="friends" :badge="applyFriendsCount<=0?null:applyFriendsCount" replace
                     to="/friends">好友
    </van-tabbar-item>
    <van-tabbar-item icon="chat-o" name="chat" replace to="/public_chat">聊天厅</van-tabbar-item>
    <van-tabbar-item to="/team" icon="search" name="team">队伍</van-tabbar-item>
    <van-tabbar-item to="/user" icon="friends-o" name="user">个人</van-tabbar-item>
  </van-tabbar>

</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {useRoute, useRouter} from "vue-router";
import routes from "../config/route.ts";
import request from "../plugins/myAxios";
import qs from "qs";

const router = useRouter();
const route = useRoute();

const DEFAULT_TITLE = 'Hsu聚友缘';
const title = ref(DEFAULT_TITLE);
const applyFriendsCount = ref(0)
const recordId = ref([])

const NOT_SHOW_NAVBAR_AND_TABBAR = ["/user/login", '/user/register']
const SHOW_SEARCH = ["/", '/team', '/public_chat', '/user', '/apply']

/**
 * 根据路由切换标题
 */
router.beforeEach((to, from) => {
  const toPath = to.path;
  const route = routes.find((route) => {
    return toPath == route.path;
  })
  title.value = route?.title ?? DEFAULT_TITLE;
})

const onLift = () => {
  router.back()
};
const onRight = async () => {
  if (!SHOW_SEARCH.includes(route.path)) {
    const read = await request.get("/friend/read", {
      params: {
        ids: recordId.value
      }, paramsSerializer: {
        serialize: (params) => {
          return qs.stringify(params, {indices: false})
        }
      }
    })
    if (read) {
      recordId.value.length = 0
      applyFriendsCount.value = 0
    }
    await router.push("/apply")
  } else {
    await router.push("/search")
  }
};
const getRecord =async () => {
  const records = await request.get("/friend/getRecords")
  records.forEach(record => {
    if (record.status == 0) {
      recordId.value.push(record.id)
    }
  })
}

onMounted(async () => {
  const urlParams = new URLSearchParams(window.location.search);
  const code = urlParams.get('code');
  if (code){
    const data = await request.post("/login/loginInfo", {
      code: code
    })
  }
  if (route.path!=="/"){
    applyFriendsCount.value = await onChange()
    await getRecord()
  }
})
const active = ref('name');

const onChange = async () => {
  if (active.value === "friends") {
    await getRecord()
  }
  return applyFriendsCount.value = await request.get("/friend/getRecordCount")
}

const loading = ref(true);

</script>

<style scoped>
#content {
  padding-bottom: 50px;
}
</style>